/**
 * 2015，thor.com，all rights reserved。
 * 
 * Project：		total-core
 * Filename：	SequenceGenerator.java
 * Created：		2015年12月16日
 * Creator：		thor
 */
package com.thor.palmmall.util.billnumber;

import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.thor.commons.util.Assert;
import com.thor.dao.BasicDao;
import com.thor.util.ApplicationContextUtils;

/**
 * @author thor
 *
 */
public class SequenceGenerator extends BasicDao implements ISequenceGenerator {

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
	public long nextValue(SequenceSpec seq) throws Exception {
		Assert.assertArgumentNotNull(seq, "seq");
		return getGenerator(getDatabaseName()).nextValue(seq);
	}

	private ISequenceGenerator getGenerator(String databaseName) {
		if (databaseName.toUpperCase().indexOf("MYSQL") >= 0) {
			return ApplicationContextUtils.getBean("mysqlSequenceDao", ISequenceGenerator.class);
		} else {
			return ApplicationContextUtils.getBean("oracleSequenceDao", ISequenceGenerator.class);
		}
	}

	@SuppressWarnings("deprecation")
	public String getDatabaseName() throws Exception {
		String databaseName = ((HibernateEntityManager) em).getSession().connection().getMetaData().getDatabaseProductName();
		return databaseName;
	}

}
